<script setup lang="ts">
import { Picker, Popup, showNotify } from "vant";
import { reactive } from "vue";
import { areaList } from "./citys.ts";
import axios from "axios";
import { useConfigStore } from "@/stores/models/config";
import { Loading } from "@/components/Overlay";

const configStore = useConfigStore();

const popupData = reactive<{
    visible: boolean;
    loading: boolean;
}>({
    visible: false,
    loading: false
});

const handleShow = (): void => {
    popupData.visible = true;
};

const handleCancel = () => {
    popupData.visible = false;
};

defineExpose({ show: handleShow });

const handleConfirm = async (e: any): Promise<void> => {
    popupData.loading = true;
    try {
        await axios({
            method: "post",
            url: `http://${configStore.device_ip}/set/city`,
            data: {
                loc: e.selectedValues[2],
                city: e.selectedOptions[2].text
            }
        });
        configStore.$patch({
            weather: {
                loc: e.selectedValues[2],
                city: e.selectedOptions[2].text
            }
        });
        showNotify({ type: "success", message: "设置成功" });
        popupData.visible = false;
    } catch (error) {
        showNotify({ type: "danger", message: "设置失败" });
        console.log(error);
    } finally {
        popupData.loading = false;
    }
};
</script>
<template>
    <Popup
        :z-index="10"
        v-model:show="popupData.visible"
        :close-on-click-overlay="!popupData.loading"
        position="bottom"
        :lazy-render="false"
        class="color-picker-popup"
    >
        <Picker
            title="选择地区"
            :columns="areaList"
            @cancel="handleCancel"
            @confirm="handleConfirm"
        ></Picker>
    </Popup>
    <Loading :show="popupData.loading" text="设置中..." />
</template>
